package test;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

public class JPanelLayoutExample extends JFrame {
    public JPanelLayoutExample() {
        super("JPanel布局示例");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建contentPane
        JPanel contentPane = new JPanel();
        setContentPane(contentPane);

        // 创建JPanel和布局管理器
        JPanel panel = new JPanel(new GridBagLayout());
        contentPane.add(panel);

        // 创建组件
        JLabel label1 = new JLabel("组件1");
        JLabel label2 = new JLabel("组件2");

        // 创建GridBagConstraints
        GridBagConstraints constraints = new GridBagConstraints();

        // 设置组件1的约束
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets.left = 10; // 设置左侧边距
        constraints.insets.top = 10; // 设置顶部边距
        panel.add(label1, constraints);

        // 设置组件2的约束
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets.top = 5; // 设置顶部边距
        panel.add(label2, constraints);

        // 调整窗口大小并显示
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        JPanelLayoutExample example = new JPanelLayoutExample();
    }
}

